package com.jingdianjichi.wx.controller;

import com.jingdianjichi.wx.handler.WxCahtMsgFactory;
import com.jingdianjichi.wx.handler.WxChatMsgHandler;
import com.jingdianjichi.wx.utils.MessageUtil;
import com.jingdianjichi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class CallBackController {

    private  static  final  String token = "admwqrq";

    @Resource
    private WxCahtMsgFactory wxCahtMsgFactory;
    @RequestMapping("/test")
    public String test(){
        return "hello word";
    }

    /**
     * 回调消息校验
     * @return
     */
    @GetMapping("/callback")
    public String callBack(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr")  String echostr){
        log.info("get验签请求参数，signature:{},timestamp:{},nonce:{},echostr:{}",
                signature,timestamp,nonce,echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)){
            return echostr;
        }
        return "unkown";
    }

    @PostMapping(value = "callback",produces = "application/xml;charset=UTF-8")
    public String callBack(
            @RequestBody String requetBody,
            @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature",required = false)  String msgSignature){
        log.info("get验签请求参数，requetBody:{},signature:{},timestamp:{},nonce:{},msgSignature:{}",
                requetBody,signature,timestamp,nonce,msgSignature);
        Map<String, String> msgMap = MessageUtil.parseXml(requetBody);
        String event = msgMap.get("Event")==null ? "":msgMap.get("Event");
        String msgType = msgMap.get("MsgType");
        log.info("msgType:{},event:{}", msgType, event);
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)){
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxhandler = wxCahtMsgFactory.getHandlerByMsgTYPE(msgTypeKey);
        if (Objects.isNull(wxhandler)){
            return "unknow";
        }
        String replyContent = wxhandler.dealMsg(msgMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }
}
